package com.cardone.generator.template;

import java.io.File;
import java.util.List;
import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import org.apache.commons.io.FileUtils;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.CollectionUtils;

import com.cardone.common.template.util.TemplateUtils;
import com.cardone.generator.mapper.EntityMapper;
import com.cardone.generator.mapper.PoMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;

/**
 * 创建索引模板
 *
 * @author yaohaitao
 *
 */
@Getter
@Setter
@Accessors(chain = true)
public class RunCreateIndexTemplate implements RunTemplate {
	private Configuration configuration;

	private List<EntityMapper> entityMapperList;

	private String outputDir;

	@Override
	public List<PoMapper> findListPoMapper() {
		final List<PoMapper> poMapperList = Lists.newArrayList();

		if (CollectionUtils.isEmpty(this.entityMapperList)) {
			return poMapperList;
		}

		for (final EntityMapper entityMapper : this.entityMapperList) {
			poMapperList.add(entityMapper);
		}

		return poMapperList;
	}

	@Override
	public void run() throws Exception {
		final String templateString = "${outputDir!}/createIndex.sql";

		final Map<String, Object> contextMap = Maps.newHashMap();

		contextMap.put("outputDir", this.outputDir);

		final String filePathName = TemplateUtils.processString(templateString, contextMap);

		final File file = new File(filePathName);

		if (file.exists()) {
			FileUtils.deleteQuietly(file);
		}

		final String templateName = "createIndex.ftl";

		final freemarker.template.Template template = this.configuration.getTemplate(templateName);

		final Map<String, Object> model = Maps.newHashMap();

		model.put("entityMapperList", this.entityMapperList);

		model.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());

		final String data = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

		FileUtils.writeStringToFile(file, data);
	}
}
